package com.genius.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.genius.annotation.PreLoginAuth;
import com.genius.auth.bo.EmailCheckBO;
import com.genius.auth.bo.UpdatePasswordBO;
import com.genius.auth.qo.EmailQO;
import com.genius.core.JSONResult;
import com.genius.enums.ResponseType;
import com.genius.mq.EmailMQConfig;
import com.genius.service.MenuService;
import com.genius.service.NoticeService;
import com.genius.service.NoticeUserService;
import com.genius.service.UserService;
import com.genius.system.bo.ReadNoticeBO;
import com.genius.system.bo.SelectNoticeByPageBO;
import com.genius.system.bo.UpdateUserInfoBO;
import com.genius.system.pojo.Menu;
import com.genius.system.pojo.Notice;
import com.genius.system.pojo.User;
import com.genius.utils.CheckUtils;
import com.genius.utils.FileUtils;
import com.genius.utils.PageUtils;
import com.genius.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("/index")
@Api(value = "首页展示接口", tags = {"用于首页展示的接口"})
public class IndexController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private NoticeUserService noticeUserService;

    @Autowired
    private UserService userService;

    @Autowired
    private CheckUtils checkUtils;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sayWelcome")
    @ApiOperation(value = "获取欢迎信息", notes = "获取欢迎信息", httpMethod = "GET")
    public JSONResult sayWelcome(){
        return JSONResult.ok("欢迎使用GK物联网后台系统，请通过前端地址访问");
    }

    @GetMapping("/getVideoUrl")
    @ApiOperation(value = "获取视频地址", notes = "获取视频地址", httpMethod = "GET")
    @PreLoginAuth
    public JSONResult getVideoUrl(){
        return JSONResult.ok("https://emos-1307515289.cos.ap-beijing.myqcloud.com/video/cloudAquarium.mp4");
    }

    @GetMapping("getUserInfo")
    @ApiOperation(value = "用户信息",notes = "获取用户信息", httpMethod = "GET")
    @PreLoginAuth
    public JSONResult getUserInfo() {
        // 权限集合
        Set<String> permissions = SecurityUtils.getLoginUser().getPermissions();
        User user = userService.selectUserById(SecurityUtils.getUserId());
        Map<String,Object> result = new HashMap<>();
        result.put("user",user);
        result.put("permissions", permissions);
        return JSONResult.ok(result);
    }

    @PostMapping("/updateUserInfo")
    @ApiOperation(value = "修改个人信息",notes = "修改个人信息", httpMethod = "POST")
    @PreLoginAuth
    public JSONResult updateUserInfo(@Valid @RequestBody UpdateUserInfoBO updateUserInfoBO) {
        Long userId = SecurityUtils.getUserId();
        User user = new User();
        user.setUserId(userId);
        user.setAvatar(updateUserInfoBO.getAvatar());
        int rows = userService.updateUser(user);
        Map<String,Object> result = new HashMap<>();
        result.put("rows",rows);
        return JSONResult.ok(result);
    }

    @GetMapping("getRouters")
    @ApiOperation(value = "路由信息",notes = "获取路由信息", httpMethod = "GET")
    @PreLoginAuth
    public JSONResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        Map<String,Object> result = new HashMap<>();
        if(SecurityUtils.getLoginUser().getUser().getIsRoot()){
            List<Menu> menus = menuService.selectAllMenu(new Menu());
            result.put("menus",menus);
        }else{
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("userId",userId);
            List<Menu> menus = menuService.selectMenuByUserId(hashMap);
            result.put("menus",menus);
        }
        return JSONResult.ok(result);
    }

    @GetMapping("/getNoticeCount")
    @ApiOperation(value = "获取消息数量", notes = "获取登陆人消息数量", httpMethod = "GET")
    @PreLoginAuth
    public JSONResult getNoticeCount(){
        Long userId = SecurityUtils.getUserId();
        int noticeCount = noticeUserService.selectNoticeCountByUserId(userId);
        return JSONResult.ok(noticeCount);
    }

    @PostMapping("/getNoticeListByUser")
    @ApiOperation(value = "获取当前用户消息列表", notes = "获取当前用户消息列表", httpMethod = "POST")
    @PreLoginAuth
    public JSONResult getNoticeListByUser(@Valid @RequestBody SelectNoticeByPageBO selectNoticeByIdBO){
        int pageNum = selectNoticeByIdBO.getPageNum();
        int pageSize = selectNoticeByIdBO.getPageSize();
        Long userId = SecurityUtils.getUserId();
        PageUtils.startPage(pageNum,pageSize);
        List<Notice> noticeList = noticeService.selectNoticeByUserId(userId);
        Map<String,Object> result = PageUtils.getResultTableData(noticeList);
        return JSONResult.ok(result);
    }

    @PostMapping("/readNotice")
    @ApiOperation(value = "已阅消息",notes = "已阅消息", httpMethod = "POST")
    @PreLoginAuth
    public JSONResult readNotice(@Valid @RequestBody ReadNoticeBO revokeNoticeBO) {
        Long[] noticeUserIds = revokeNoticeBO.getNoticeUserIds();
        int rows = noticeUserService.readNoticeUserByIds(noticeUserIds);
        Map<String,Object> result = new HashMap<>();
        result.put("rows",rows);
        return JSONResult.ok(result);
    }

    /**
     * 获取邮箱验证码
     * @param emailCheckBO 邮箱
     * @return 邮箱验证码发送结果
     */
    @PostMapping("/getEmailCheckCode")
    @ApiOperation(value = "获取邮箱验证码",notes = "获取邮箱验证码", httpMethod = "POST")
    public JSONResult getEmailCheckCode(@Valid @RequestBody EmailCheckBO emailCheckBO){
        String emailCheckCode = checkUtils.getEmailVerificationCode(emailCheckBO.getEmail());
        EmailQO emailQO = new EmailQO();
        String[] users = {emailCheckBO.getEmail()};
        emailQO.setUsers(users);
        emailQO.setSubject("邮箱验证码已送达");
        Date nowDate = new Date();
        String nowTime = DateUtil.format(nowDate, "yyyy-MM-dd HH:mm:ss");
        Date expireDate = DateUtil.offsetMinute(nowDate,1);
        String expireTime = DateUtil.format(expireDate, "yyyy-MM-dd HH:mm:ss");
        String content = FileUtils.buildContent("html/emailRegisterCheck.html",emailCheckCode,nowTime,expireTime);
        emailQO.setContent(content);
        // 发送邮箱
        rabbitTemplate.convertAndSend(EmailMQConfig.EMAIL_EXCHANGE, EmailMQConfig.ROUTING_KEY_EMAIL_SEND_REGISTER,JSONUtil.toJsonStr(emailQO));
        return JSONResult.ok("验证码已发送至邮箱");
    }

    /**
     * 修改密码
     * @return 路由信息
     */
    @PostMapping("setNewPassword")
    @ApiOperation(value = "修改密码",notes = "修改密码", httpMethod = "POST")
    @PreLoginAuth
    public JSONResult setNewPassword(@Valid @RequestBody UpdatePasswordBO updatePasswordBO){
        String password = updatePasswordBO.getPassword();
        User user = SecurityUtils.getUser();
        checkUtils.checkEmailVerificationCode(user.getEmail(),updatePasswordBO.getCheckCode());
        String encryptPassword = SecurityUtils.encryptPassword(password);
        user.setUpdateBy(user.getUsername());
        user.setUsername(user.getUsername());
        user.setPassword(encryptPassword);
        int rows = userService.updatePassword(user);
        if(rows > 0){
            return JSONResult.ok("修改成功");
        }
        return JSONResult.errorCustom(ResponseType.FAILED);
    }

}
